package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入第0个过滤器");
        //先拿到响应和请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //对请求路径判断是否有/admin/login,如果有则为登录请求,放行
        System.out.println(request.getURI().getPath());
        System.out.println(request.getPath());
        if(request.getURI().getPath().contains("/admin/login")){
            //放行操作
            return chain.filter(exchange);
        }

        //如果不是登陆请求,则查询请求头中是否携带token
        String token = request.getHeaders().getFirst("token");
        //如果token为空,则在响应体中设置未授权403
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        //token存在,解析是否签名有效
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();

            //响应一个未授权
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }

        //token合法,放行操作
        return chain.filter(exchange);


    }

    @Override
    public int getOrder() {
        return 0;
    }
}
